# -*- coding:utf-8 -*-
import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import hashlib
from utils.HttpUtils import HttpUtils



class ShangCheng_PingLun():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            'xy-common-params': 'platform=android&deviceId=09c26e69-4dd3-3923-98e0-192bbb80103e&device_fingerprint=201910311912389a3f5a74e15c33655d76f5418a561bc001f3988f5a5bb100&device_fingerprint1=201910311912389a3f5a74e15c33655d76f5418a561bc001f3988f5a5bb100&versionName=6.39.0&channel=CPTS&sid=session.1575801730382713578617&t=1587516598&fid=1575801853006cdd75295012140dbcde9eb9ec66a1bd&uis=light&identifier_flag=2',
            'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.0.2; CHE-TL00H Build/HonorCHE-TL00H) Resolution/720*1280 Version/6.39.0 Build/6390099 Device/(HUAWEI;CHE-TL00H) discover/6.39.0 NetType/WiFi',
            'shield': '06e405495cef037c37ecf2f246a6de0f',
            'xy-platform-info': 'platform=android&build=6390099&deviceId=09c26e69-4dd3-3923-98e0-192bbb80103e',
            'Host': 'www.xiaohongshu.com',
            'Connection': 'Keep-Alive',
            'Accept-Encoding': 'gzip'
        }

    def get_contents(self):
        postData = {
            "start": "",
            "num": "10",
            "show_priority_sub_comments": "0",
            "source": "explore",
            "platform": "android",
            "deviceId": "09c26e69-4dd3-3923-98e0-192bbb80103e",
            "device_fingerprint": "201910311912389a3f5a74e15c33655d76f5418a561bc001f3988f5a5bb100",
            "device_fingerprint1": "201910311912389a3f5a74e15c33655d76f5418a561bc001f3988f5a5bb100",
            "versionName": "6.35.0",
            "channel": "Guanfang",
            "sid": "session.1575801730382713578617",
            "lang": "zh-Hans",
            "t": "1584601208",
            "fid": "1575801853006cdd75295012140dbcde9eb9ec66a1bd",
            # "sign": "effc8e35376ea5a7db9e8ac1b2463928",
        }

        sign = self.sign_with_query_items(postData)
        postData['sign'] = sign
        # url = "https://www.xiaohongshu.com/api/store/review/5b7a526970e7520da07599b5/product_review?page=0&per_page=10&tab=2&fold=0&tag=&sid=session.1572779772974525401812"
        url = "https://www.xiaohongshu.com/api/sns/v5/note/5e5855ad0000000001005771/comment/list"
        html = HttpUtils.do_request("GET", url, self.headers, postData)
        datajson = json.loads(html.text)
        for d in datajson['data']['reviews']:
            dict = dict()
            dict['createTime'] = datetime.fromtimestamp(int(d['createTime']))
            dict['userInfo'] = d['userInfo']['userName']
            dict['userId'] = d['userInfo']['userId']
            dict['text'] = d['text']
            # 购买的商品
            dict['variants'] = d['variants']['name']
            dict['variants'] = d['variants']['value']

    def sign_with_query_items(self, data):
        import urllib
        import hashlib
        udid = data['deviceId']
        # 将请求参数按key排序
        data = {k: data[k] for k in sorted(data.keys())}
        # 拼接成字符串
        data_str = ''
        for k, v in data.items():
            data_str += '{}={}'.format(k, v)
        data_str = urllib.parse.quote(data_str, 'utf-8')

        # 将url encode之后的字符串的每个字符与对应的udid字符进行异或原形
        xor_str = ''
        udid_length = len(udid)
        for i in range(len(data_str)):
            data_char = data_str[i]
            udid_index = int(i % udid_length)
            udid_char = udid[udid_index]
            rst = ord(udid_char) ^ ord(data_char)
            xor_str += str(rst)

        # 对异或后的字符串MD5
        md5 = hashlib.md5()
        md5.update(xor_str.encode())
        md5_str = md5.hexdigest()

        # 将MD5后的字符串和udid拼接起来，再次MD5
        md5_str += udid
        md5 = hashlib.md5()
        md5.update(md5_str.encode())
        md5_str = md5.hexdigest()
        return md5_str

    def md5hex(self, word):
        m = hashlib.md5()
        m.update(word.encode("utf-8"))
        return m.hexdigest()

    def sortedDictValues3(self, adict):
        keys = adict.keys()
        keys.sort
        return map(adict.get, keys)

    def get_sign(self, Arr):
        Str=''
        Keys=sorted(Arr.keys())

        for item in Keys:
            if item!='':
                Str=Str+item+'%3D'+Arr[item]
        deviceId=Arr['deviceId']
        v1_2 = bytearray(Str, 'utf-8')
        v5_1 = ''
        v3_2 = 0
        v2 = 0
        v4_1=bytearray(deviceId, 'utf-8')

        while v2<len(v1_2):
            v5_1 = v5_1 + str(v1_2[v2] ^ v4_1[v3_2 ])
            v3_2 = (v3_2 + 1) % len(v4_1)
            v2 = v2 + 1

        sign = self.md5hex(self.md5hex(v5_1)+deviceId)
        return sign


if __name__ == '__main__':
    shangcheng_pinglun = ShangCheng_PingLun()
    shangcheng_pinglun.get_contents()